//
//  XTEmoticonKeyBoard.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/21.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

let XTEmoticonCollectionCellId = "XTEmoticonCollectionCellId"
class XTEmoticonKeyBoard: UIView {

        //  MARK: -懒加载控件-
    //toolBar
    private lazy var toolBar:XTEmoticonToolBar = {
        let toolBar = XTEmoticonToolBar(frame: CGRectZero)
        return toolBar
    }()
    
    //展示表情的colletionView部分
    private lazy var emoticonCollectionView:UICollectionView = {
        let flowLayout=UICollectionViewFlowLayout()
        flowLayout.scrollDirection = .Horizontal
        let view = UICollectionView(frame: CGRectZero, collectionViewLayout:flowLayout)
        view.pagingEnabled = true
        view.showsHorizontalScrollIndicator = false
        view.showsVerticalScrollIndicator = false
        view.registerClass(XTEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: XTEmoticonCollectionCellId)
        view.dataSource = self
        view.delegate = self
        return view
    }()
    
    
    //分页控件
    private lazy var pageControl : UIPageControl = {
        let ctr = UIPageControl()
        
        ctr.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        ctr.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        
        return ctr
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        //默认选择的表情
        let indexPath = NSIndexPath(forItem: 0, inSection: 0);
        setPageControlData(indexPath)
        
        
        backgroundColor = UIColor.yellowColor()
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(pageControl)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.height.equalTo(44)
        }
        //toolBar里对应的执行方法里所含的闭包，进行点击按钮时，上面的表情键盘的切换
        toolBar.emoticonToolBarBtnClickClosure = {(btnType:XTEmoticonToolBarBtnType)->() in
            let indexPath : NSIndexPath
            switch btnType{
            case .Normal:
                print("Normal")
                indexPath = NSIndexPath(forItem: 0, inSection: 0)
            case .Emoji:
                print("Emoji")
                indexPath = NSIndexPath(forItem: 0, inSection: 1)
            case .Lxh:
                print("Lxh")
                indexPath = NSIndexPath(forItem: 0, inSection: 2)
            }
            self.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            self.setPageControlData(indexPath)
        }
        pageControl.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self.toolBar.snp_top)
            make.height.equalTo(10)
        }
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
    }
    
    //通过修改子控件的方法来调整collectionView的布局
    override func layoutSubviews() {
        super.layoutSubviews()
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.minimumLineSpacing = 0
        flowLayout.itemSize = emoticonCollectionView.size
    }
    
    //控制pageControl数据
    private func setPageControlData(indexPath:NSIndexPath){
        pageControl.numberOfPages = XTEmoticonTool.sharedTools.allEmoticons[indexPath.section].count
        pageControl.currentPage = indexPath.item
    }

    
}


    //  MARK: -扩展KBView，实现collectionView的数据源方法-
extension XTEmoticonKeyBoard:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        print("section----\(XTEmoticonTool.sharedTools.allEmoticons.count)")
        return XTEmoticonTool.sharedTools.allEmoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("item-----\(XTEmoticonTool.sharedTools.allEmoticons[section].count)")
        return XTEmoticonTool.sharedTools.allEmoticons[section].count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XTEmoticonCollectionCellId, forIndexPath: indexPath) as! XTEmoticonCollectionViewCell
        
        cell.emoticonArray = XTEmoticonTool.sharedTools.allEmoticons[indexPath.section][indexPath.item]
        
        return cell
    }

    //代理方法
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let contentOffsetX = scrollView.contentOffset.x
        
        //取到当前显示的cell visible:看得见的
        let cells = emoticonCollectionView.visibleCells().sort { (firstCell, secondCell) -> Bool in
            return firstCell.x < secondCell.x
        }
        
        //判断哪个cell显示得更多
        if cells.count == 2{
            let firstCell = cells.first!
            let secondCell = cells.last!
            
            let firstCellContentOffsetX = abs(firstCell.x - contentOffsetX)
            let secondCellContentOffsetX = abs(secondCell.x - contentOffsetX)
            
            var indexPath = NSIndexPath()
            if firstCellContentOffsetX < secondCellContentOffsetX{
                indexPath = emoticonCollectionView.indexPathForCell(firstCell)!
            }else{
                indexPath = emoticonCollectionView.indexPathForCell(secondCell)!
            }
            
            let section = indexPath.section
            self.toolBar.changeEmoticonBtnWithSection(section)
            //设置选中按钮
            setPageControlData(indexPath)
        }
    }

}
